﻿/*
jQuery plugin 
http://tutorialzine.com/2011/02/converting-jquery-code-plugin/
*/
$(document).ready(function() {
    $('select').tzSelect();
});

(function($) {
    $.fn.tzSelect = function(options) {
        options = $.extend({
            render: function(option) {
                return $('<li>', {html:option.text()});
            },
            "class":''
        },options);
        return this.each(function() {

            var select = $(this);
            var selectBoxContainer = $('<div>', {
                width: select.outerWidth(),
                "class": 'tzSelect',
                html: '<div class="selectBox"></div>'
            });

            var dropDown = $('<ul>', {
                "class": 'dropDown'
            });

            var selectBox = selectBoxContainer.find('.selectBox');

            // Looping though the options of the original select element
            select.find('option').each(function(i) {
                var $option = $(this);

                if (i == select.attr('selectedIndex')) {
                    selectBox.html($option.text());
                }


                if ($option.data('skip')) {
                    return true;
                }

                  var li = options.render($option);
                li.on('click',function() {
                    selectBox.html($option.text());
                    dropDown.trigger('hide');

                    select.val($option.val());

                    return false;
                });

                dropDown.append(li);
                return true;
            });

            selectBoxContainer.append(dropDown.hide());
            select.hide().after(selectBoxContainer);

            dropDown.bind('hide', function() {
                if (dropDown.is(":animated")) {
                    return false;
                }
                selectBox.removeClass('expanded');
                dropDown.slideUp();
            });

            dropDown.bind('show', function() {

                if (dropDown.is(':animated')) {
                    return false;
                }
                selectBox.addClass('expanded');
                dropDown.slideDown();
            });

            dropDown.bind('toggle', function() {
                if (selectBox.hasClass('expanded')) {
                    dropDown.trigger('hide');
                } else {
                    dropDown.trigger('show');
                }
            });

            selectBox.click(function() {
                dropDown.trigger('toggle');
                return false;
            });

            $(document).click(function() {
                dropDown.trigger('hide');
            });
        });
    };
})(jQuery);